<?php

namespace App\Jobs;

use App\Models\Project;
use App\Models\ProjectAgreement;
use App\Models\ProjectExportRecord;
use App\Models\ProjectExportRecordsDetail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class ExportAgreementLogJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    // public $tries = 2;

    // public $maxExceptions = 2;

    // public function retryUntil()
    // {
    //     return now()->addMinutes(5);
    // }


    /** @var ProjectAgreement */
    protected $agreement;

    /** @var Project  */
    protected $project;

    protected $result;

    protected $adminUser;

    protected $fileName;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($result, $adminUser, Project $project, $fileName)
    {
        $this->result = $result;
        $this->adminUser = $adminUser;
        $this->project = $project;
        $this->fileName = $fileName;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Log::info('----------导出记录开始了----------' . json_encode($this->result));
            $pay_status_success = 0;
            $pay_status_fail = 0;

            foreach ($this->result as $key => $val) {
                if (isset($val['pay_status'])) {
                    if ($val['pay_status'] == 2) {
                        $pay_status_success += 1;
                    } elseif ($val['pay_status'] == -1) {
                        $pay_status_fail += 1;
                    }
                }
            }
            Log::info('----------记录支付状态:成功:----------' . $pay_status_success);
            Log::info('----------记录支付状态:失败:----------' . $pay_status_fail);
            // todo 只有财务导出的时候, 需要留痕
            $export_records = [
                'file_name' => $this->fileName,
                'project_id' => $this->project['id'],
                 'project_code' => isset($this->project['project_sn']) ? $this->project['project_sn'] : '',
                'admin_id' => $this->adminUser['id'],
                'roles' => json_encode($this->adminUser->roles),
                'pay_fail' => $pay_status_fail,
                'pay_success' => $pay_status_success,
                'pay_total' => count($this->result),
            ];


            $export_records_info = ProjectExportRecord::create($export_records);
            $data = [];
            foreach ($this->result as $key => &$val) {
                $val['project_agreement_id'] = $val['id'];
                $val['records_id'] = $export_records_info['id'];
                $val['created_at'] = Carbon::now();
                $val['audit_fee'] = 0;
                $val['project_id'] = $this->project['id'];
                $val['user_id'] = $val['user_id'];
                unset($val['id'], $val['active_name'], $val['agreement_file'], $val['agreement_file_sign'], $val['company_short'], $val['is_contract'], $val['project_code'], $val['project_name'], $val['project_sn'], $val['project_status'], $val['sponsor']);
                array_push($data, $val);
            }
            Log::info('导出记录详情:' . json_encode($data));
            ProjectExportRecordsDetail::insert($data);
        } catch (\Exception $e) {
            Log::info('----------catch----------', ['exception' => json_encode($e)]);
            $this->failed($e);
        }
    }

    /**
     * 处理任务失败。
     *
     * @param  \Throwable  $exception
     * @return void
     */
    public function failed(\Throwable $exception)
    {
        error_log('生成协议失败, msg: ' . $exception->getMessage());
    }
}
